package com.xingda.packing.dmds.config;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xingda.packing.dmds.config.appset.AppSetParam;
import com.xingda.packing.dmds.config.appset.AppSetUrl;
import com.xingda.packing.dmds.domain.PackProductionLine;
import com.xingda.packing.dmds.enums.AlarmTriggerType;
import com.xingda.packing.dmds.events.EventCreater;
import com.xingda.packing.dmds.minitor.entity.*;
import com.xingda.packing.dmds.minitor.mapper.*;
import com.xingda.packing.dmds.minitor.service.IPkDownWheelService;
import com.xingda.packing.dmds.plc.service.PlcDirectiveService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * 增加定时任务开关
 */
@Configuration("SchedulingDMDSConfig")
//启用定时任务
@EnableScheduling
//配置文件读取是否启用此配置
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class SchedulingConfig {
    @Resource
    IPkDownWheelService pkDownWheelService;
    @Resource
    EventCreater eventCreater;
    @Resource
    PkPlcAlarmMapper pkPlcAlarmMapper;
    @Resource
    PkAlarmTypeMapper pkAlarmTypeMapper;
    @Resource
    PkEventsMapper pkEventsMapper;
    @Resource
    PkRuntimeMapper pkRuntimeMapper;
    @Resource
    PkPlcLogMapper pkPlcLogMapper;
    @Resource
    private PackProductionLine packProductionLine;
    @Resource
    private PlcDirectiveService plcDirectiveService;
    @Resource
    private PkActionMapper pkActionMapper;
    @Resource
    private PkTaskMapper pkTaskMapper;

    /**
     * 删除n分钟之前的卸轮记录
     */
    @Scheduled(cron = "0 0/5 * * * ? ")
    @Async
    public void removeDownWheel() {
        if (packProductionLine.getEnv().startsWith("xd-prod")) {
            pkDownWheelService.removeMinuteAgo();
            if (AppSetParam.auto_reomve_packing_downwheel) {
                pkDownWheelService.removePacking();
            }
        }
    }

    @Scheduled(cron = "0/1 * * * * ? ")
    @Async
    public void monitorPlcStatus() {
        if (packProductionLine.getEnv().startsWith("xd-prod")) {
            if (plcDirectiveService.getPlcStatus()) {
                plcDirectiveService.writePlcStatus();
            }
        }
    }
//
//    @Scheduled(cron = "0/5 * * * * ? ")
//    @Async
//    public void monitorUploadStatus() {
//        LambdaQueryWrapper<PkTask> pkTaskLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        pkTaskLambdaQueryWrapper.isNull(PkTask::getEndTime).eq(PkTask::getType, 1).eq(PkTask::isUpload, 1);
//        List<PkTask> pkTasks = pkTaskMapper.selectList(pkTaskLambdaQueryWrapper);
//        if (!pkTasks.isEmpty() && AppSetParam.is_floor_upload) {
//
//        }
//    }

    @Scheduled(cron = "0 0/1 * * * ? ")
    @Async
    public void getDownWheel() {
        if (packProductionLine.getEnv().startsWith("xd-prod")) {
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("area", packProductionLine.getArea());
            String s = HttpUtil.get(AppSetUrl.down_wheel_url, paramMap);
            List<PkDownWheel> pkDownWheels = JSONArray.parseArray(s, PkDownWheel.class);
            pkDownWheelService.saveBatch(pkDownWheels);
        }
    }

    @Scheduled(cron = "0 0 0 * * ?")
    @Async
    public void deleteTask() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);
        LambdaQueryWrapper<PkEvents> eventsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        eventsLambdaQueryWrapper.le(PkEvents::getCreateTime, calendar.getTime()).orderByDesc(PkEvents::getCreateTime);
        pkEventsMapper.delete(eventsLambdaQueryWrapper);
        LambdaQueryWrapper<PkRuntime> runtimeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        runtimeLambdaQueryWrapper.le(PkRuntime::getCreateTime, calendar.getTime()).orderByDesc(PkRuntime::getCreateTime);
        pkRuntimeMapper.delete(runtimeLambdaQueryWrapper);
        LambdaQueryWrapper<PkPlcLog> pkPlcLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pkPlcLogLambdaQueryWrapper.le(PkPlcLog::getCreateTime, calendar.getTime()).orderByDesc(PkPlcLog::getCreateTime);
        pkPlcLogMapper.delete(pkPlcLogLambdaQueryWrapper);
    }

    @Scheduled(cron = "0/5 * * * * ? ")
    @Async
    public void monitorRobotAction() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -AppSetParam.robot_not_move_alarm_minute);
        //检测1
        LambdaQueryWrapper<PkAction> pkActionQueryWrapper1 = Wrappers.lambdaQuery();
        pkActionQueryWrapper1.ge(PkAction::getStartTime, calendar.getTime()).orderByDesc(PkAction::getStartTime).eq(PkAction::getArea, 1);
        List<PkAction> pkAction1 = pkActionMapper.selectList(pkActionQueryWrapper1);
        eventCreater.createTriggerAlarm(AlarmTriggerType.ROBOT_TIMEOUT_NOT_MOVE, pkAction1.isEmpty(), 1);
        //检测2
        LambdaQueryWrapper<PkAction> pkActionQueryWrapper2 = Wrappers.lambdaQuery();
        pkActionQueryWrapper2.ge(PkAction::getStartTime, calendar.getTime()).orderByDesc(PkAction::getStartTime).eq(PkAction::getArea, 2);
        List<PkAction> pkAction2 = pkActionMapper.selectList(pkActionQueryWrapper2);
        eventCreater.createTriggerAlarm(AlarmTriggerType.ROBOT_TIMEOUT_NOT_MOVE, pkAction2.isEmpty(), 2);

    }

//    @Scheduled(cron = "0/2 * * * * ? ")
//    @Async
//    public void monitorPlcAlarm() {
//        if (packProductionLine.getEnv().startsWith("xd-prod")) {
//            List<PlcItem> plcItemList = new ArrayList<>();
//            for (PkPlcAlarm pkPlcAlarm : pkPlcAlarmMapper.selectList(null)) {
//                plcItemList.add(new PlcItem(pkPlcAlarm.getContent(), pkPlcAlarm.getAddress()));
//            }
//            JSONObject jsonObject = plcDirectiveService.readVals(plcItemList);
//            for (String next : jsonObject.keySet()) {
//                LambdaQueryWrapper<PkPlcAlarm> pkPlcAlarmLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                pkPlcAlarmLambdaQueryWrapper.eq(PkPlcAlarm::getContent, next);
//                PkPlcAlarm pkPlcAlarm = pkPlcAlarmMapper.selectOne(pkPlcAlarmLambdaQueryWrapper);
//                LambdaQueryWrapper<PkAlarmType> pkAlarmTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                pkAlarmTypeLambdaQueryWrapper.eq(PkAlarmType::getId, pkPlcAlarm.getId());
//                eventCreater.createTriggerAlarm(pkAlarmTypeMapper.selectOne(pkAlarmTypeLambdaQueryWrapper), jsonObject.getBooleanValue(next), pkPlcAlarm.getArea());
//            }
//        }
//    }
}
